package com.msunsoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.msunsoft.common.BaseService;
import com.msunsoft.exception.BusinessException;
import com.msunsoft.support.dozer.DozerMapperHelper;
import com.msunsoft.system.mybatis.dao.SysRoleMapper;
import com.msunsoft.system.mybatis.model.SysRole;
import com.msunsoft.system.vo.RoleVo;

@Service
public class RoleService extends BaseService<SysRoleMapper, SysRole> {

    public List<RoleVo> listAllPaged() {

        List<SysRole> list = this.dao.listAll();

        if ((list != null) && !list.isEmpty()) {
            List<RoleVo> voList = new ArrayList();
            for (SysRole role : list) {
                RoleVo roleVo = DozerMapperHelper.map(role, RoleVo.class);
                List<Integer> menuIds = this.dao.selectMenuIdsByRoleId(role.getId());
                roleVo.setMenuIds(menuIds);
                voList.add(roleVo);
            }
            return voList;
        }
        return null;
    }

    public List<SysRole> listAll() {
        return this.dao.listAll();
    }

    //    public List<Role> listAll2() {
    //        return this.dao.listAll2();
    //    }

    // TODO 数据权限暂时不做
    public Integer insert(RoleVo vo) {
        SysRole role = DozerMapperHelper.map(vo, SysRole.class);

        super.insert(role);
        Integer roleId = role.getId();

        // 插入到sys_role_menu中间表
        List<Integer> menuIds = vo.getMenuIds();
        if ((menuIds != null) && !menuIds.isEmpty()) {
            this.dao.insertRoleMenu(roleId, menuIds);
        }
        return 0;
    }

    public Integer updateById(RoleVo vo) {
        // 1. 修改实体
        SysRole role = DozerMapperHelper.map(vo, SysRole.class);
        super.updateById(role);

        // 2. 清除中间表
        this.dao.deleteRoleMenuById(vo.getId());

        // 3. 插入中间表
        List<Integer> menuIds = vo.getMenuIds();
        if ((menuIds != null) && !menuIds.isEmpty()) {
            this.dao.insertRoleMenu(vo.getId(), menuIds);
        }
        return 0;
    }

    public boolean deleteRoleById(Integer id) {
        // 1. 查询该角色下有多少用户
        Integer count = this.dao.selectCountAdminIdByRoleId(id);
        // 2. 角色下存在用户, 不允许删除
        if (count != 0) {
            throw new BusinessException("非法操作!该角色下有用户存在, 该角色不允许删除!");
        }
        super.deleteById(id);
        return true;
    }
}
